﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ForumServer;
using ForumServer.Forum;
using log4net;
using ForumLibrary;
using ForumLibrary.Data;

namespace ForumGUI
{
    public partial class LoginFrame : Form
    {
        private ForumManager _manager;
        private string _username;
        private string _password;
        private ILog logger;

        public string UserName { get { return _username; } set { _username = value; } }
        public string Password { get { return _password; } set { _password = value; } }

        public LoginFrame(ref ForumManager manager)
        {
            InitializeComponent();
            _manager = manager;
            _username = "";
            _password = "";
        }

        private void login_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_username))
            {
                MessageBox.Show("Please enter username!!!");
                return;
            }
            if (string.IsNullOrEmpty(_password))
            {
                MessageBox.Show("Incorrect password!!!");
                return;
            }

            string res = "";
            try
            {
                string passEncode = ForumManager.Encoder.HashEncode(_password);
                res = _manager.login(_username, passEncode.ToLower());
            }
            catch
            {
                MessageBox.Show("Server is down. Please try again in a few minutes");
                return;
            }
            if (res.Contains("Login Complete:"))
            {
                Logger log = new Logger(_username, "Client");
                logger = log.getLogger();
                MessageBox.Show(res);
                ClientController clientController = new ClientController(_username, ref _manager, ref logger);

                clientController.pushForm(this);
                ForumsFrame forumsFrame = new ForumsFrame(ref clientController,ref _manager);
                forumsFrame.Visible = true;
                this.Visible = false;
            }
            else
                MessageBox.Show(res);
            
        }

      
        private void passwordTextBox_TextChanged(object sender, EventArgs e)
        {
            TextBox t = (TextBox)sender;
            _password = t.Text;
           
        }

        private void UserNameBox_TextChanged(object sender, EventArgs e)
        {
            TextBox t = (TextBox)sender;
            _username = t.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Dispose(false);
            RegisterFrame r = new RegisterFrame(ref this._manager);
            r.Visible = true;
        }

    }
}
